# main.py
from fastapi import FastAPI, HTTPException
from typing import Optional, List, Dict

app = FastAPI()

# 临时存储
fake_db = []

# 普通 Item 类
class Item:
    def __init__(
        self,
        name: str,
        price: float,
        description: Optional[str] = None,
        tax: Optional[float] = None
    ):
        self.name = name
        self.price = price
        self.description = description
        self.tax = tax

# 手动验证函数
def validate_item(data: dict):
    required_fields = ["name", "price"]
    for field in required_fields:
        if field not in data:
            raise HTTPException(400, f"Missing required field: {field}")
    
    if not isinstance(data.get("name"), str):
        raise HTTPException(400, "Name must be a string")
    
    if not isinstance(data.get("price"), (int, float)):
        raise HTTPException(400, "Price must be a number")
    
    return data

@app.post("/items/")
async def create_item(item_data: dict):
    validated_data = validate_item(item_data)
    new_item = Item(**validated_data)
    new_item.id = len(fake_db) + 1
    fake_db.append(new_item.__dict__)
    return new_item.__dict__

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id < 1 or item_id > len(fake_db):
        raise HTTPException(404, "Item not found")
    return fake_db[item_id-1]
  
  
  
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)
    print("Server started at http://127.0.0.1:8000")
    print("Press Ctrl+C to stop the server")
